package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialdeliveryEntity;
import city.spring.modules.material.service.MaterialSettingService;
import city.spring.modules.material.service.MaterialdeliveryService;
import city.spring.modules.material.vo.MaterialdeliveryVO;
import city.spring.modules.material.vo.PrintDeliveryVO;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：物资出库
 *
 * @author 谢金婷
 * @date 2020-07-02 13:41:43
 */
@RestController
@RequestMapping("/materialdelivery")
public class MaterialdeliveryController extends ApiController {
    private final MaterialdeliveryService materialdeliveryService;
    private final EmployeeService employeeService;
    private final MaterialSettingService materialSettingService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MaterialdeliveryEntity, ?>> entityOrderFields;

    public MaterialdeliveryController(MaterialdeliveryService materialdeliveryService, EmployeeService employeeService, MaterialSettingService materialSettingService) {
        this.materialdeliveryService = materialdeliveryService;
        this.employeeService = employeeService;
        this.materialSettingService = materialSettingService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialdeliveryEntity::getId);
        entityOrderFields.add(MaterialdeliveryEntity::getMaterialreceiptId);
        entityOrderFields.add(MaterialdeliveryEntity::getDestination);
        entityOrderFields.add(MaterialdeliveryEntity::getDeliverydate);
        entityOrderFields.add(MaterialdeliveryEntity::getUserId);
        entityOrderFields.add(MaterialdeliveryEntity::getUsersId);
        entityOrderFields.add(MaterialdeliveryEntity::getGmtCreate);
        entityOrderFields.add(MaterialdeliveryEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>物资出库</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MaterialdeliveryEntity entity) {
        LambdaQueryChainWrapper<MaterialdeliveryEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>物资出库</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MaterialdeliveryVO entity, Date[] deliverydate) {

        QueryWrapper<? extends MaterialdeliveryEntity> queryWrapper = buildQuery(entity);
        if (deliverydate != null && deliverydate.length == 2) {
            queryWrapper.ge("t1.deliverydate", deliverydate[0]);
            queryWrapper.le("t1.deliverydate", deliverydate[1]);
        }
        return success(materialdeliveryService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

//        LambdaQueryChainWrapper<MaterialdeliveryEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MaterialdeliveryEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MaterialdeliveryEntity record : page.getRecords()) {
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUserId());
//                record.setName(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUserId(null);
//                record.setName("< 找不到领用人 >");
//            }
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUsersId());
//                record.setUsername(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUsersId(null);
//                record.setUsername("< 找不到登记人 >");
//            }
//            try {
//                MaterialSettingEntity materialSettingEntity = materialSettingService.getById(record.getMaterialId());
//                record.setMname(materialSettingEntity.getName());
//            } catch (Exception ignore) {
//                record.setMaterialId(null);
//                record.setMname("< 找不到物资 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 获取一个 <strong>物资出库</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

        QueryWrapper<MaterialdeliveryVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialdeliveryVO> records = materialdeliveryService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));

//        return success(materialdeliveryService.getMaterialdeliveryById(id));
    }

    /**
     * 添加一个 <strong>物资出库</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MaterialdeliveryEntity entity, @NonNull Principal user) {
        materialdeliveryService.saveMaterialdelivery(entity, user);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(entity, headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>物资出库</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MaterialdeliveryEntity entity) {
        entity.setId(id);
        materialdeliveryService.updateMaterialdelivery(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>物资出库</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        materialdeliveryService.deleteMaterialdelivery(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>物资出库</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        materialdeliveryService.deleteMaterialdelivery(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialdeliveryEntity> buildLambdaQuery(MaterialdeliveryEntity entity) {
        LambdaQueryChainWrapper<MaterialdeliveryEntity> lambdaQuery = materialdeliveryService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, MaterialdeliveryEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDestination()), MaterialdeliveryEntity::getDestination, entity.getDestination());
        lambdaQuery.eq(entity.getDeliverydate() != null, MaterialdeliveryEntity::getDeliverydate, entity.getDeliverydate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUserId()), MaterialdeliveryEntity::getUserId, entity.getUserId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUsersId()), MaterialdeliveryEntity::getUsersId, entity.getUsersId());
        lambdaQuery.eq(entity.getGmtCreate() != null, MaterialdeliveryEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MaterialdeliveryEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialdeliveryEntity> buildQuery(MaterialdeliveryVO entity) {
        QueryWrapper<MaterialdeliveryEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getDepartmentName()), "t2.title", entity.getDepartmentName());
        wrapper.like(StringUtils.isNotBlank(entity.getUserId()), "t1.user_id", entity.getUserId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t3.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getUsersId()), "t1.users_id", entity.getUsersId());
        wrapper.like(StringUtils.isNotBlank(entity.getUsername()), "t4.name", entity.getUsername());
        wrapper.like(entity.getMaterialreceiptId() != null, "t1.materialreceipt_id", entity.getMaterialreceiptId());
//        wrapper.like(entity.getApplicationdate() != null, "t3.applicationdate", entity.getApplicationdate());
        return wrapper;
    }

    /**
     * 打印出库单
     *
     * @param ids
     * @return
     */
    @PostMapping("/getPrintDelivery")
    public Object getPrintDelivery(@RequestBody List<String> ids) {
        PrintDeliveryVO data = materialdeliveryService.getPrintDelivery(ids);
        return success(data);
    }

    /**
     * 出库单作废
     *
     * @param id
     * @param entity
     * @return
     */
    @PutMapping("/checkCancellation/{id}")
    public Object checkCancellation(@PathVariable String id, @RequestBody MaterialdeliveryEntity entity) {
        materialdeliveryService.checkCancellation(id, entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
